package fatworm.query;

import fatworm.storage.table.*;
import fatworm.util.Lib;

public class ProductPlan implements Plan {
	
	private Plan p1, p2;
	private Schema sch = new Schema();
	
	public ProductPlan(Plan p1, Plan p2) {
		this.p1 = p1;
		this.p2 = p2;
		
		sch.addAll(p1.getSchema());
		sch.addAll(p2.getSchema());
	}
	
	public Scan open() {
		return new ProductScan(p1.open(), p2.open());
	}
	
	public int blocksAccessed() {
		return p1.blocksAccessed() + p1.recordsOutput() * p2.blocksAccessed();
	}
	
	public int recordsOutput() {
		return p1.recordsOutput() * p2.recordsOutput();
	}
	
	public int distinctValues(String name) {
		if (p1.getSchema().hasField(name))
			return p1.distinctValues(name);
		else
			if (p2.getSchema().hasField(name))
				return p2.distinctValues(name);
			else
				Lib.assertNotReached();
		
		return 0;
	}
	
	public Schema getSchema() {
		return sch;
	}
}